/* tslint:disable:typedef */
import {ChangeDetectionStrategy, ChangeDetectorRef, Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {PageHeaderType} from '../../../../share/components/page-header/page-header.component';
import {FormArray, FormBuilder, FormGroup, Validators} from '@angular/forms';
import {OptionsInterface} from '../../../../core/services/types';
import {MapPipe, MapSet} from '../../../../share/pipes/map.pipe';
import {TestQuestionService} from '../../../../core/services/http/test-question/test-question.service';
import {NzUploadFile} from 'ng-zorro-antd/upload';

@Component({
  selector: 'app-add-edit-test',
  templateUrl: './add-edit-test.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})

export class AddEditTestComponent implements OnInit {
  validateForm!: FormGroup;
  @Output() returnBack: EventEmitter<any>;
  @Input() id!: number;
  @Input() currentPageNum!: number;
  testquestionOptionDtos: OptionsInterface[] = [];
  difficultyOptions: OptionsInterface[] = [];
  listOfOptions: OptionsInterface[] = [];
  pageHeaderInfo: Partial<PageHeaderType> = {
    title: '编辑页面',
    breadcrumb: ['考试教育', '试题编辑']
  };
  uploadUrl: string;
  showUploadList = {
    showPreviewIcon: true,
    showRemoveIcon: true,
    hidePreviewIconInNonImage: true,
  };
  previewImage: string | undefined = '';
  previewVisible = false;
  fileList: any[] = [];
  answerFileList: any = {};


  constructor(private fb: FormBuilder, private dataService: TestQuestionService, private cdr: ChangeDetectorRef) {
    this.uploadUrl = '/site/upload';
    this.returnBack = new EventEmitter<any>();

  }

  get items() {
    return this.validateForm.controls['questionOptionDtos'] as FormArray;
  }

  createRow(): FormGroup {
    return this.fb.group({
      answerFlag: [null],
      content: [null, [Validators.required, Validators.maxLength(255)]],
      pictureUrl: [null],
    });
  }

  add(): void {
    this.items.push(this.createRow());
  }

  del(index: number): void {
    this.items.removeAt(index);
  }

  /*题库下拉请求数据*/
  selectList(): Promise<any> {
    return new Promise(resolve => {
      this.dataService.getQuestionBankSelectList({pageSize: 0, pageNum: 0}).subscribe(datas => {
        datas.list.forEach(item => {
          this.listOfOptions.push({value: item.id, label: item.name});
        });
        resolve();
      });
    });
  }


  async submit() {
    Object.keys(this.validateForm.controls).forEach(key => {
      this.validateForm.controls[key].markAsDirty();
      this.validateForm.controls[key].updateValueAndValidity();
    });
    if ((this.validateForm.invalid) || this.items.invalid) {
      return;
    }
    const params = this.validateForm.getRawValue();
    let submitHandel = null;
    if (!this.id) {
      submitHandel = this.dataService.addTestQuestion(params).subscribe();
    } else {
      params.id = this.id;
      submitHandel = this.dataService.editTestQuestion(params).subscribe();
    }
    await submitHandel;
    this.returnBack.emit({refesh: false, pageNo: this.currentPageNum});
  }

  initForm(): void {
    this.validateForm = this.fb.group({
      type: [null, [Validators.required]],
      difficultyGrade: [null, [Validators.required]],
      questionBlanks: [null, [Validators.required]],
      content: [null, [Validators.required, Validators.maxLength(255)]],
      pictureUrl: [null, []],
      analysis: [null, [Validators.maxLength(255)]],
      questionOptionDtos: this.fb.array([])
    });
  }

  uploadFn(e: any, type: 'pictureUrl' | 'picture', i?: number): void {
    if (e.type === 'success') {
      if (e.file.response.code === 0) {
        if (type === 'pictureUrl') {
          this.validateForm.get('pictureUrl')!.setValue(e.file.response.data);
        } else {
          // @ts-ignore
          this.items.at(i).get('pictureUrl')!.setValue(e.file.response.data);
        }
      }
    }
  }

  handlePreview(file: NzUploadFile): void {
    this.previewImage = file.url || file.thumbUrl;
    this.previewVisible = true;
  }

  handleRemove(file: NzUploadFile): boolean {
    // @ts-ignore
    this.validateForm.get('pictureUrl').setValue(null);
    this.validateForm.updateValueAndValidity();
    return true;
  }

  /*调取详情接口数据*/
  getDetail(): void {
    this.dataService.getTestQuestionDetail(this.id).subscribe(resData => {
      if (resData.pictureUrl !== null) {
        this.fileList = [{
          url: resData.pictureUrl,
        }];
      }
      // @ts-ignore
      resData.questionOptions.forEach((itemData, index) => {
        const field = this.createRow();
        field.patchValue(itemData);
        this.items.push(field);
        if (itemData.pictureUrl === null) {
          return;
        }
        this.answerFileList[index] = [{
          url: itemData.pictureUrl,
          thumbUrl: itemData.pictureUrl,
        }];
      });
      this.validateForm.patchValue(resData);
      this.cdr.markForCheck();
    });
  }


  /*返回*/
  returnToList(): void {
    this.returnBack.emit({refesh: false, pageNo: this.currentPageNum});
  }

  async ngOnInit(): Promise<any> {
    this.initForm();
    this.testquestionOptionDtos = [...MapPipe.transformMapToArray(MapSet.topicType)];
    this.difficultyOptions = [...MapPipe.transformMapToArray(MapSet.difficultyLevel)];
    await this.selectList();
    if (this.id) {
      this.getDetail();
    }
  }

}
